package cn.live.kyle.questionnaire.question;

import org.w3c.dom.Element;

import cn.live.kyle.questionnaire.R;
import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

public class QuestionText extends QuestionItem {
	private EditText mEditText;

	public QuestionText(Element element, QuestionPage page) {
		super(element, page);

		ViewGroup container = page.getQuestionViewContainer();
		Context context = container.getContext();
		mQuestionItemView = LayoutInflater.from(context).inflate(
				R.layout.question_text, container, false);

		mEditText = (EditText) mQuestionItemView
				.findViewById(R.id.questionEditText);

		String inputType = mElement
				.getAttribute(QuestionDomParser.ATTR_INPUT_TYPE);
		if (inputType != null
				&& inputType.equals(QuestionDomParser.ATTR_INPUT_TYPE_PHONE)) {
			mEditText.setInputType(InputType.TYPE_CLASS_PHONE);
		} else if (inputType != null
				&& inputType.equals(QuestionDomParser.ATTR_INPUT_TYPE_DECIMAL)) {
			mEditText.setInputType(InputType.TYPE_CLASS_NUMBER
					| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		}

		String answer = mElement.getAttribute(QuestionDomParser.ATTR_ANSWER);
		mEditText.setText(answer);
		int len = answer.length();
		mEditText.setSelection(len);
		mEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
				checkAnswer();
				if (mIsAnswered) {
					String answer = mEditText.getText().toString();
					mElement.setAttribute(QuestionDomParser.ATTR_ANSWER, answer);
				}
				mQuestionPage.onQuestionItemStateChanged();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

		});

		TextView titleView = (TextView) mQuestionItemView
				.findViewById(R.id.questionTitle);
		String title = mElement.getAttribute(QuestionDomParser.ATTR_TITLE);
		if (title != null && title.length() > 0) {
			titleView.setText(title);
			titleView.setVisibility(View.VISIBLE);
		}

		checkAnswer();
	}

	private void checkAnswer() {
		String answer = mEditText.getText().toString();
		if (answer.length() > 0) {
			mIsAnswered = true;
		} else {
			mIsAnswered = false;
		}
	}

	@Override
	public void onFinish() {
		super.onFinish();
		InputMethodManager imm = (InputMethodManager) (mEditText.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE));
		imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
	}

}
